import React, { useEffect, useState, useReducer} from 'react';
import sdk from 'qcloud-iotexplorer-h5-panel-sdk';
import * as echarts from 'echarts/core';
import { Radio } from 'antd';
import classNames from "classnames";
// import the core library.
import ReactEChartsCore from 'echarts-for-react/lib/core';
import {
    GridComponent, ToolboxComponent , TooltipComponent , DataZoomComponent
} from 'echarts/components';
import {
    LineChart
} from 'echarts/charts';
import {
    CanvasRenderer
} from 'echarts/renderers';

echarts.use(
    [GridComponent, LineChart, CanvasRenderer, ToolboxComponent , TooltipComponent , DataZoomComponent]
);

import { IMGURL,APIURL } from '../utils/common';
const thirdUserNo = "para_user1"
const cutimeoptions = [
  { label: '近一周', value: 'd' },
  { label: '本月', value: 'm' },
  { label: '本年', value: 'y' },
];
// 当前时间
const current_Date = new Date()
const current_time = new Date()
const startTime =current_Date.valueOf()
const endTime = current_time
var now = new Date(); // 当前日期
var nowDayOfWeek = now.getDay(); // 今天本周的第几天
var nowDay = now.getDate(); // 当前日
var nowMonth = now.getMonth(); // 当前月
var nowYear = now.getYear(); // 当前年
nowYear += (nowYear < 2000) ? 1900 : 0;
  
var DateUtil = {
    /**
     * 获得当前日期
     *
     * @returns
     */
    getNowDay() {
        return this.formatDate(new Date());
    },
    /**
     * 获得本周的开始时间
     *
     * @returns
     */
    getStartDayOfWeek() {
        var day = nowDayOfWeek || 7;
        return this.formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 1 - day));
    },
    /**
     * 获得本周的结束时间
     *
     * @returns
     */
    getEndDayOfWeek() {
        var day = nowDayOfWeek || 7;
        return this.formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 7 - day));
    },
    /**
     * 获得本月的开始时间
     *
     * @returns
     */
    getStartDayOfMonth() {
        var monthStartDate = new Date(nowYear, nowMonth, 1);
        return this.formatDate(monthStartDate);
    },
    /**
     * 获得本月的结束时间
     *
     * @returns
     */
    getEndDayOfMonth() {
        var monthEndDate = new Date(nowYear, nowMonth, this.getMonthDays());
        return this.formatDate(monthEndDate);
    },
    /**
     * 获得本月天数
     *
     * @returns
     */
    getMonthDays() {
        var monthStartDate = new Date(nowYear, nowMonth, 1);
        var monthEndDate = new Date(nowYear, nowMonth + 1, 1);
        var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
        return days;
    },
    getStartDayOfYear() {
      var d = new Date();
      var n = d.getFullYear()+"-01-01";
      return n;
    },
    getEndDayOfYear() {
      var d = new Date();
      var n = d.getFullYear()+"-12-31";
      return n;
    },
    /**
     * @param 日期格式化
     * @returns {String}
     */
    formatDate(date) {
        var myyear = date.getFullYear();
        var mymonth = date.getMonth() + 1;
        var myweekday = date.getDate();
  
        if (mymonth < 10) {
            mymonth = "0" + mymonth;
        }
        if (myweekday < 10) {
            myweekday = "0" + myweekday;
        }
        return (myyear + "-" + mymonth + "-" + myweekday);
    },
    formatTimer(timer) {
      var date = new Date(timer);
      Y = date.getFullYear() + '-';
      M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
      D = date.getDate() + ' ';
      h = date.getHours() + ':';
      m = date.getMinutes() + ':';
      s = date.getSeconds(); 
      console.log(Y+M+D+h+m+s); //呀麻碟
      return (Y+M+D);
  }
};
{ /* end*/}
const windowHeight = window.innerHeight || document.documentElement.clientHeight;
let myuserInfo = sdk.userInfo
// 趋势
export function QsPage(){
  const [sdkReady, setSdkReady] = useState(false);
	useEffect(() =>  {
		h5PanelSdk.sdkReady().then(() =>  setSdkReady(true));
	}, []);
  const [tzl, settzl] = useState([]);
  // const  [qsweight, setqsweight] = useState([]);
  // const  [bmi, setbmi] = useState("d");
  // const startTime =Date.parse(DateUtil.getNowDay())
  // const [cutime,setcutime]=useState()
  // 开始和截止时间
  // const startTime =Date.parse(DateUtil.getStartDayOfWeek())
  // const endTime =Date.parse(DateUtil.getEndDayOfWeek())
  // 处理年月日时间的reducer
  const initialCount = {
    cutime:"d",
    startTimetext:DateUtil.getStartDayOfWeek(),
    endTimetext:DateUtil.getEndDayOfWeek(),
    startTime: Date.parse(DateUtil.getStartDayOfWeek()),
    endTime: Date.parse(DateUtil.getEndDayOfWeek())
  };
  // function init(initialCount) {
  //   return {echartstime: initialCount};
  // }
  function reducer(state, action) {
    switch (action.type) {
      case 'd':
        return {
          cutime:action.type,
          startTimetext:DateUtil.getStartDayOfWeek(),
          endTimetext:DateUtil.getEndDayOfWeek(),
          startTime: Date.parse(DateUtil.getStartDayOfWeek()),
          endTime: Date.parse(DateUtil.getEndDayOfWeek())
        };
        break
      case 'm':
        return {
          cutime:action.type,
          startTimetext:DateUtil.getStartDayOfMonth(),
          endTimetext:DateUtil.getEndDayOfMonth(),
          startTime: Date.parse(DateUtil.getStartDayOfMonth()),
          endTime: Date.parse(DateUtil.getEndDayOfMonth())};
      case 'y':
        return {
          cutime:action.type,
          startTimetext:DateUtil.getStartDayOfYear(),
          endTimetext:DateUtil.getEndDayOfYear(),
          startTime: Date.parse(DateUtil.getStartDayOfYear()),
          endTime: Date.parse(DateUtil.getEndDayOfYear())};
      default:
        throw new Error();
    }
  }
  const [state, dispatch] = useReducer(reducer, initialCount);
  const {startTime,endTime} = state
  const getThirdUserData =(tempDataName,cutime) =>{
    var request = require('superAgent')
    request
    .post(APIURL+'getThirdUserData')
    .send({
      "productId":sdk.productId,
      "deviceName":sdk.deviceName,
      "wx_unionid":myuserInfo.UserID,
      "startTime":startTime,
      "endTime":endTime + 57600000,
      "tempDataName":tempDataName
    })
    // .set('Content-Type', 'application/text')
    .end(function(err, res){
      console.log(res)
      const qsweight = []
      let tzc = {
        weight:[],bmi:[],fat_num:[],bodywater:[],muscle:[],ctime:[]
      }
      if(res.body.code == 1){
        // var JkcardUdata = res.body.data.data.slice(0,7).reverse()
        // BMI: "20.420401464462"
        // BMR: "0"
        // boneKg: "0"
        // device_id: 766
        // fatKg: "0"
        // fatRate: "0"
        // id: 1330
        // muscleKg: "0"
        // notFatWeight: "0"
        // option_time: 1649668718810
        // option_type: 1
        // third_user_id: 231
        // user_id: 4
        // waterKg: "0"
        var JkcardUdata = res.body.data.data
        if(JkcardUdata.length ==0){
          tzc = {
            weight:[0],bmi:[0],fat_num:[0],bodywater:[0],muscle:[0],ctime:["暂无数据"]
          }
          settzl(tzc)
        }else{
          // switch(cutime){
          //   case 'd':
          //     JkcardUdata = JkcardUdata.slice(0,14)
          //     break
          //   case 'm':
          //     JkcardUdata = JkcardUdata.slice(0,7)
          //     break
          //   case 'y':
          //     JkcardUdata = JkcardUdata
          //     break
          // }
          for(let i in JkcardUdata){
            var tempctime = DateUtil.formatDate(new Date(JkcardUdata[i].option_time))
            // switch(cutime){
            //   case 'd':
            //     if(i==0){
            //       tempctime = tempctime.split("-")[1]+"月-"+tempctime.split("-")[2]
            //     }else{
            //       tempctime = tempctime.split("-")[2]
            //     }
            //     break
            //   case 'm':
            //     if(i==0){
            //       tempctime = tempctime.split("-")[0]+"年-"+tempctime.split("-")[1]+"/"+tempctime.split("-")[2]
            //     }else{
            //       tempctime = tempctime.split("-")[1]+"/"+tempctime.split("-")[2]
            //     }
            //     break
            //   case 'y':
            //     tempctime = tempctime.split("-")[1]+"/"+tempctime.split("-")[2]
            //     break
            // }
            qsweight.push(JkcardUdata[i].weight)
            tzc.weight.push(JkcardUdata[i].weight)
            tzc.bmi.push(parseFloat(JkcardUdata[i].BMI).toFixed(2))
            tzc.fat_num.push(JkcardUdata[i].fatKg)
            tzc.bodywater.push(JkcardUdata[i].waterKg)
            tzc.muscle.push(JkcardUdata[i].muscleKg)
            tzc.ctime.push(tempctime)
          }
          console.log('qsweight',qsweight)
          console.log('tzc',tzc)
          settzl(tzc);
          // setqsweight(qsweight)
        }
      }else{
        console.log('服务器'+res)
      }
    })
  }
  useEffect(() => {
    getThirdUserData("weight,BMI,BMR,fatKg,muscleKg,waterKg,boneKg,notFatWeight,fatRate",state.cutime)
  }, [state])
  function Ywtab() {
    const [sdkReady, setSdkReady] = useState(false);
    useEffect(() =>  {
      h5PanelSdk.sdkReady().then(() =>  setSdkReady(true));
    }, []);
    const echartData = {
      ywbtn:0,
      edata:tzl.weight,
      timelist:tzl.ctime,
    };
    // function init(initialCount) {
    //   return {echartstime: initialCount};
    // }
    function echartreducer(state, action) {
      switch(action.type)
			{
				case 0: 
          if(tzl.weight.length <=0){

          }
          return {
            ywbtn:action.type,
            edata:tzl.weight,
            timelist:tzl.ctime,
          }
				case 1:
          return {
            ywbtn:action.type,
            edata:tzl.bmi,
            timelist:tzl.ctime,
          }
				case 2:
          return {
            ywbtn:action.type,
            edata:tzl.fat_num,
            timelist:tzl.ctime,
          }
				case 3:
          return {
            ywbtn:action.type,
            edata:tzl.bodywater,
            timelist:tzl.ctime,
          }
				case 4:
          return {
            ywbtn:action.type,
            edata:tzl.muscle,
            timelist:tzl.ctime,
          }
        default:
          return {
            ywbtn:action.type,
            edata:tzl.weight,
            timelist:tzl.ctime,
          }
      }
    }
    const [echartstate, echartdispatch] = useReducer(echartreducer, echartData);
    const twqsoption = {
      grid:{
        show:false,
      },
      // legend:{
      //   top: 0,
      //   right:0
      // },
      tooltip: {
        trigger: 'axis',
        position: function (pt) {
          return [pt[0], '10%'];
        }
      },
      toolbox: {
        show:true,
        iconStyle:{
          borderColor:"#FFF"
        },
        feature: {
          dataZoom: {
            yAxisIndex: 'none',
            show: true,
          },
          dataView: { show: false,readOnly: false },
          magicType: { show: false,type: ['line', 'bar'] },
          restore: {emphasis:{iconStyle:{color:"#FFF"}}},
          saveAsImage: {show: false,}
        }
      },
      xAxis: {
          type: 'category',
          data: echartstate.timelist,
          axisLine:{
            show:true,
            lineStyle:{
              color:'rgba(255, 255, 255, 0.5)'
            }
          }
      },
      yAxis: {
          // show:false,
          type: 'value',
          axisLine:{
            show:false,
          }
      },
      textStyle:{
        color:"#FFF"
      },
      dataZoom: [
        {
          type: 'slider',
          minSpan:0,
          start: 0,
          end: 30,
        }
      ],
      series: [{
          data: echartstate.edata,
          type: 'line',
          color: '#FFF',
          smooth: true,
          symbol:'circle', 
          symbolSize :5,
          label:{
            show:true,
            color:'#FFF'
          },
          labelLine:{
            show:true,
          },
          areaStyle:{
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                  offset: 0, color: 'rgba(255, 255, 255, 0.5)' // 0% 处的颜色
              }, {
                  offset: 1, color: 'rgba(255, 255, 255, 0)' // 100% 处的颜色
              }],
              global: false // 缺省为 false
            },
            shadowColor: 'rgba(255, 255, 255, 0.5)',
            shadowBlur: 8,
            opacity:0.3
          }
      }],
    };
    const clickYwbtn = e => {
      echartdispatch({type:e})
    }
    // 底部切换图片名称列表
    const imglist =[
      "weight","bmi","bafat","moisu","muscle"
    ]
    return !sdkReady ? <div > loading...</div >  : (
        <div className="pd">
          <div id="qxchart" className="qxchartcon">
            <ReactEChartsCore
              echarts={echarts}
              option={twqsoption}
              notMerge={true}
              lazyUpdate={true}
              theme={"theme_name"}
              // onChartReady={this.onChartReadyCallback}
              // onEvents={EventsDict}
              style={{ height: '300px', width: '100%'}}
            />
          </div>
          <div className="twbtnlist fl-rsac pdtb">
            {
              imglist.map((val,index)=>{
                return (
                <div className={classNames("twbtnimg fl-cc",{ 'selected': echartstate.ywbtn ==index } )} onClick={(e)=>clickYwbtn(index,e)} key={index}>
                  <img src={echartstate.ywbtn ==index ?IMGURL+"btn_"+val+".png" : IMGURL+"btn_"+val+"-ed.png"} />
                </div>
                )
              })
            }
          </div>
        </div>
    )
  };
  const selectcutime =(e)=>{
    console.log('radio checked', e.target.value);
    // setcutime(e.target.value)
    dispatch({type:e.target.value})
    // twqsoption.resize({
    //   width: 800,
    //   height: 400
    // });
  }
  return !sdkReady ? <div > loading...</div >  : (
    <div className="qsPage">
      <div className="navtit">趋势曲线</div>
      <div className="pdlr fl-rc">
        <div style={{display:"none"}}>时间: {state.startTimetext}-{state.endTimetext}</div>
        <div>
          <Radio.Group
          options={cutimeoptions}
          onChange={selectcutime}
          value={state.cutime}
          optionType="button"
          size="small"
          buttonStyle="outline"
        />
        </div>
      </div>
      <Ywtab />
    </div>
  )
}
